package test2.redis;

import java.util.UUID;

import redis.clients.jedis.Jedis;

public class RedisDistributedLock {
	
	Jedis jedis = new Jedis();
	
	String key = UUID.randomUUID().toString();
	long timeout = 30L;
	
	public RedisDistributedLock(String key, long timeout) {
		this.key = key;
		this.timeout = timeout;
	}
	
	public RedisDistributedLock(String key) {
		this.key = key;
	}
	
	public RedisDistributedLock(long timeout) {
		this.timeout = timeout;
	}
	
	public RedisDistributedLock() {
		
	}
	
	public void lock(LockService lockService) {
		try {
			while(true) {
				Long result = jedis.setnx(key, (now() + timeout) + "");
				System.out.println(Thread.currentThread().getName() + "result="+result);
				if(result==0) {
					System.out.println("锁失败");
					String a = jedis.get(key);
					long b = Long.parseLong(a);
					if(now()>b) {
						System.out.println(Thread.currentThread().getName() + "当前时间大于当前锁过期时间，证明当前锁已经失效，可以删除当前锁变为自己的锁");
//						try {
//							//睡5秒，模拟并发，多个请求同时判断出锁过期，准备删除
//							Thread.sleep(8000);
//						} catch (InterruptedException e) {
//							e.printStackTrace();
//						}
						String c = jedis.getSet(key, (now() + timeout) + "");
						System.out.println(Thread.currentThread().getName() + "原来的过期时间="+c);
						long d = Long.parseLong(c);
						System.out.println(Thread.currentThread().getName() + "当前的时间="+now());
						if(now()>d) {
							break;
						}
					} 
				} else {
					break;
				}
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			lockService.deal();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jedis.close();
		}
	}
	
	private long now() {
		return System.currentTimeMillis();
	}
	
	public interface LockService {
		void deal();
	}
}
